﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace BlueMarineWindowsFormsClient
{
    public class ImageTool
    {
        public Image ResizeImage(Image img)
        {
            int originalW = img.Width;
            int originalH = img.Height;
            int resizedW = 120;
            int resizedH = 180;
            float per;

            if (originalW <= originalH)
            {
                per = 120/(float) originalW;
                resizedH = (int) (originalH*per);
            }
            else
            {
                per = (float) 180/480;
                resizedW = (int) (originalW*per);
            }
            var bmp = new Bitmap(resizedW, resizedH);
            Graphics graphic = Graphics.FromImage(bmp);
            graphic.SmoothingMode = SmoothingMode.AntiAlias;
            graphic.InterpolationMode = InterpolationMode.HighQualityBilinear;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphic.DrawImage(img, 0, 0, resizedW, resizedH);
            graphic.Dispose();
            return bmp;
        }

        public byte[] ImageToByte(Image image)
        {
            var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);
            return ms.ToArray();
        }

        public Image ByteToImage(byte[] data)
        {
            var ms = new MemoryStream(data);
            Image image = Image.FromStream(ms);
            return image;
        }

        public Byte[] ImageToByte(String imagePath)
        {
            using (var FS = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
            {
                var img = new byte[FS.Length];
                FS.Read(img, 0, Convert.ToInt32(FS.Length));
                return img;
            }
        }
    }
}